/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.Rol;
import com.tesam.gedeon.service.RolService;
import com.tesam.gedeon.service.SystemUserService;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author joelpacheco
 */
@Controller
public class RolController {

    @Autowired
    private RolService rolService;
    @Autowired
    private SystemUserController system;
    @Autowired
    private SystemUserService systemUserService;

    @RequestMapping(value = "/rol/index", method = RequestMethod.GET)
    public ModelAndView rolIndex(HttpServletRequest request, HttpServletResponse response) {

        // RequestContextUtils.getLocaleResolver(request).setLocale(request, response, new Locale(request.getParameter("language")));
        ModelAndView mv = new ModelAndView("/rol/index");
        String module = request.getParameter("module");
        if (!rolService.isNullOrEmpty(module)) {
            request.getSession().setAttribute("module", module);
        }

        System.out.println("Ingreso en el indice");
        //request.getSession().getAttribute("moduleId",request.getParameter("module"));
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/rol/new", method = RequestMethod.GET)
    public ModelAndView newRol(HttpServletRequest request) {

        Rol rol = new Rol();
        ModelAndView mv = new ModelAndView("/rol/new");
        //System.out.println("Session" + request.getSession().getAttribute("module"));
        system.loadDataSystem(mv, request);
        request.getSession().setAttribute("tokenRol", 1);
        mv.addObject("rol", rol);
        return mv;
    }

    @RequestMapping(value = "/rol/save", method = RequestMethod.POST)
    public ModelAndView saveRol(@ModelAttribute("rol") Rol rol, SessionStatus status, HttpServletRequest request) {

        String message = null;

        ModelAndView mv = new ModelAndView("redirect:/rol/index");

        String token = (request.getSession().getAttribute("tokenRol") == null) ? "" : request.getSession().getAttribute("tokenRol").toString();

        if (token == null || token.isEmpty()) {

            return mv;
        } else {

            if (rolService.save(rol) > 0) {

                request.getSession().removeAttribute("tokenRol");

                mv = new ModelAndView("/rol/index");

                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Rol " + rol.getName() + " registrado correctamente"
                        + "</div>";

                mv.addObject("message", message);

            } else {

                message = "<div class=\"alert alert-block alert-error fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Fallo! </strong>"
                        + " Ocurrio un error al tratar de registrar rol " + rol.getName() + " en el servidor"
                        + "</div>";

                mv.addObject("message", message);
            }
        }
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/rol/edit", method = RequestMethod.GET)
    public ModelAndView editRol(HttpServletRequest request) {

        ModelAndView mv = null;
        int rolId = Integer.parseInt(request.getParameter("id"));
        request.getSession().setAttribute("tokenRol", 1);
        Rol rol;
        rol = rolService.getById(rolId);
        mv = new ModelAndView("/rol/edit");
        mv.addObject("rol", rol);
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/rol/edit", method = RequestMethod.POST)
    public ModelAndView editRol(@ModelAttribute("rol") Rol rol, SessionStatus status, HttpServletRequest request) {

        String message = null;

        ModelAndView mv = new ModelAndView("redirect:/rol/index");

        String token = (request.getSession().getAttribute("tokenRol") == null) ? "" : request.getSession().getAttribute("tokenRol").toString();

        if (token == null || token.isEmpty()) {

            return mv;
        } else {

            rol.setModifiedBy(1);

            if (rolService.update(rol) > 0) {

                request.getSession().removeAttribute("tokenRol");

                mv = new ModelAndView("/rol/index");

                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Rol " + rol.getName() + " actualizado correctamente"
                        + "</div>";

                mv.addObject("message", message);

            } else {

                message = "<div class=\"alert alert-block alert-error fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Fallo! </strong>"
                        + " Ocurrio un error al tratar de actualizar rol " + rol.getName() + " en el servidor"
                        + "</div>";

                mv.addObject("message", message);
            }
        }
        return mv;
    }

    @RequestMapping(value = "/rol/delete", method = RequestMethod.GET)
    public ModelAndView deleteRol(HttpServletRequest request, SessionStatus status) {

        String message = null;
        ModelAndView mv = new ModelAndView("redirect:/rol/index");

        int rolId = Integer.parseInt(request.getParameter("id"));

        if (rolId > 0) {

            Rol rol = rolService.getById(rolId);

            if (rol != null) {

                rol.setModifiedBy(1);

                mv = new ModelAndView("/rol/index");

                if (rolService.delete(rol) > 0) {

                    status.setComplete();
                    message = "<div class=\"alert alert-block alert-success fade in\">"
                            + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                            + "<strong>Éxito! </strong>"
                            + " Rol " + rol.getName() + " eliminado correctamente"
                            + "</div>";

                    mv.addObject("message", message);

                } else {
                    message = "<div class=\"alert alert-block alert-error fade in\">"
                            + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                            + "<strong>Fallo! </strong>"
                            + " Ocurrio un error al tratar de eliminar rol " + rol.getName() + " en el servidor"
                            + "</div>";

                    mv.addObject("message", message);
                }
            }
        }
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/rol/view", method = RequestMethod.GET)
    public ModelAndView viewRol(HttpServletRequest request) {

        ModelAndView mv = null;
        int rolId = Integer.parseInt(request.getParameter("id"));
        request.getSession().setAttribute("tokenRol", 1);
        Rol rol = rolService.getById(rolId);
        System.out.println("Ingreso");
        System.out.println("User Id =>" + rol.getCreatedBy());
        rol.setSystemUser(systemUserService.getById(rol.getCreatedBy()));
        //sSystem.out.println("Entidad:" + systemUser);
        System.out.println("Salio");
        mv = new ModelAndView("/rol/view");
        mv.addObject("rol", rol);
        system.loadDataSystem(mv, request);
        return mv;
    }

    @RequestMapping(value = "/rol/treeview", method = RequestMethod.GET)
    public ModelAndView getTreeByRolAndParent() {

        List<Rol> listRolParent = null;
        StringBuilder nestable = null;
        ModelAndView mv = new ModelAndView("/rol/treeview");

        try {

            listRolParent = rolService.getAll();

            nestable = new StringBuilder("<div class=\"dd\" id=\"treeview\">");
            nestable.append("<ol class=\"dd-list\">");

            for (Rol rolParent : listRolParent) {

                if (rolParent.getRolParentId() == 0) {
                    //  System.out.println(rolParent.getId());
                    StringBuilder stringB = nestable;
                    nestable = null;
                    nestable = treeByRolAndParent(rolParent, 0, stringB);
                }
            }

            nestable.append("</ol>");
            nestable.append("</div>");

            mv.addObject("treeview", nestable.toString());

        } catch (Exception e) {
            System.out.println("Exception-RolController-getTreeByRolAndParent:" + e.getMessage());
        }
        return mv;
    }

    public StringBuilder treeByRolAndParent(Rol rol, int id, StringBuilder stringBuilder) {

        StringBuilder nestable = null;
        nestable = stringBuilder;
        List<Rol> listRol = null;

        nestable.append("<li class=\"dd-item dd3-item\" data-id=");
        nestable.append(rol.getId());
        nestable.append(">");
        nestable.append("<div class=\"dd-handle dd3-handle\"></div>");
        nestable.append("<div class=\"dd3-content\">");
        nestable.append(rol.getName());
        nestable.append("</div>");

        //Busca los hijos
        listRol = rolService.getAllByParentId(rol.getId());

        if (listRol.size() > 0) {
            nestable.append("<ol class=\"dd-list\">");
            for (Rol rolx : listRol) {

                if (rolx.getId() != 140608) {

                    nestable.append("<li class=\"dd-item dd3-item\" data-id=");
                    nestable.append(rolx.getId());
                    nestable.append(">");
                    nestable.append("<div class=\"dd-handle dd3-handle\"></div>");
                    nestable.append("<div class=\"dd3-content\">");
                    nestable.append(rolx.getName());
                    nestable.append("</div>");
                    StringBuilder stringB = nestable;
                    nestable = null;
                    nestable = getTreeViewChildren(rolx, stringB);
                    nestable.append("</li>");
                }
            }
            nestable.append("</ol>");
        }
        nestable.append("</li>");
        return nestable;
    }

    public StringBuilder getTreeViewChildren(Rol rol, StringBuilder stringBuilder) {

        StringBuilder nestable = stringBuilder;
        List<Rol> listRol = null;
        listRol = rolService.getAllByParentId(rol.getId());

        if (listRol.size() > 0) {

            nestable.append("<ol class=\"dd-list\">");
            for (Rol rolx : listRol) {

                nestable.append("<li class=\"dd-item dd3-item\" data-id=");
                nestable.append(rolx.getId());
                nestable.append(">");
                nestable.append("<div class=\"dd-handle dd3-handle\"></div>");
                nestable.append("<div class=\"dd3-content\">");
                nestable.append(rolx.getName());
                nestable.append("</div>");
                StringBuilder stringB = nestable;
                nestable = null;
                nestable = getTreeViewChildren(rolx, stringB);
                nestable.append("</li>");

            }
            nestable.append("</ol>");
            return nestable;
        } else {
            return nestable;
        }
    }

    @RequestMapping(value = "/rol/treeview", method = RequestMethod.POST)
    public @ResponseBody
    String saveTree(HttpServletRequest request) {

        String message = null;
        try {

            if (treeview(request.getParameter("treeview"), 0) > 0) {
                message = "<div class=\"alert alert-block alert-success fade in\">"
                        + "<button class=\"close\" data-dismiss=\"alert\"></button>"
                        + "<strong>Éxito! </strong>"
                        + " Cambios guardados correctamente"
                        + "</div>";
            }

        } catch (Exception e) {
            System.out.println("Exception 1:" + e.getMessage());
        }
        return message;
    }

    public int treeview(String arrayJson, int rolParentId) {
        try {

            JSONArray jsonMainArr = new JSONArray(arrayJson);

            String node = null;

            int rolId = 0;
            int isSave = 0;
            int countArrayJson = jsonMainArr.length();

            for (int i = 0; i < countArrayJson; i++) {
                JSONObject jsonObject = jsonMainArr.getJSONObject(i);
                Iterator<?> rolIterator = jsonObject.keys();

                // System.out.println("Padre id ==> "+rolParentId);

                while (rolIterator.hasNext()) {

                    node = rolIterator.next().toString();
                    rolId = jsonObject.getInt("id");

                    if (node.equalsIgnoreCase("children")) {
                        //System.out.println(jsonObject.getString("id"));
                        treeview(jsonObject.getString(node), rolId);
                    } else {
                        //rolId = jsonObject.getInt(node);
                        Rol rol = new Rol();
                        rol.setModifiedBy(1);
                        rol.setRolParentId(rolParentId);
                        rol.setId(rolId);
                        rol.setOwnerId(1);
                        isSave = rolService.updateTreeView(rol);
                        System.out.println("Save");
                    }
                }
            }
            return isSave;
        } catch (Exception e) {
            System.out.println("Exception 2 :" + e.getMessage());
        }
        return 0;
    }

    @RequestMapping(value = "/rol/ajax", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGet() {

        int cantidadRegistros = 0;
        try {
            List<Rol> list = rolService.getAllByLimit(10, 1, "id", "ASC");

            // ArrayList<Cliente> list = clienteService.getAllClientes();
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            //  System.out.println("Hola Mundo");
            if (list.size() > 0) {
                for (Rol rol : list) {
                    JSONArray arrayPut = new JSONArray();
                    arrayPut.put(rol.getId());
                    arrayPut.put(rol.getName());
                    arrayPut.put(rol.getDescription());
                    arrayPut.put(rol.getRolParentId());
                    arrayPut.put(rol.getRolParentId());
                    array.put(arrayPut);
                    // cantidadRegistros++;
                }
            }


            cantidadRegistros = rolService.getCountTotal();
            json.put("iTotalRecords", cantidadRegistros);
            json.put("iTotalDisplayRecords", cantidadRegistros);
            json.put("aaData", array);

            return json.toString();
        } catch (Exception e) {
            System.out.print("Error - Controller-doAjax:" + e.getMessage());
        }

        return null;
    }

    @RequestMapping(value = "/rol/ajax", method = RequestMethod.POST)
    public @ResponseBody
    String doAjaxPost(HttpServletRequest request) {

     
        List<Rol> listaDeRoles = null;
        int cantidadRegistros = 0;

        String[] columns = {"id", "name", "description", "datecreated"};

        String startLimit = request.getParameter("iDisplayStart");
        String endLimit = request.getParameter("iDisplayLength");
        String dataToSort = columns[Integer.valueOf(request.getParameter("iSortCol_0"))];
        String directionOfOrder = request.getParameter("sSortDir_0");
        String textSearch = request.getParameter("sSearch").toUpperCase();
        String moduleId = request.getSession().getAttribute("module").toString();
        
        int _moduleId = 0;

        if (!moduleId.isEmpty()) {
            _moduleId = Integer.parseInt(moduleId);
        }

        int _startLimit = 0;
        int _endLimit = 0;

        if (startLimit != null && !startLimit.equals("0")) {

            if (!startLimit.trim().isEmpty()) {
                _startLimit = Integer.valueOf(startLimit);
            }
        }

        if (endLimit != null && !endLimit.equals("0")) {
            if (!endLimit.trim().isEmpty()) {
                _endLimit = Integer.valueOf(endLimit);
            }
        }

        if (textSearch != null) {
            if (!textSearch.trim().isEmpty()) {
                textSearch = textSearch.trim();
                Rol rol = new Rol();
                rol.setName(textSearch);
                listaDeRoles = rolService.searchByName(rol, _startLimit,
                        (_endLimit));
                cantidadRegistros = rolService.getCountSearchByName(rol);
                return rolService.getJsonDataFromArrayList(listaDeRoles, cantidadRegistros, _moduleId);

            }
        }

        listaDeRoles = rolService.getAllByLimit(_startLimit,
                (_endLimit), dataToSort, directionOfOrder);

        cantidadRegistros = rolService.getCountTotal();

        return rolService.getJsonDataFromArrayList(listaDeRoles, cantidadRegistros, _moduleId);
    }
}
